import * as server from "@minecraft/server";
export { SummoningEntityWithData, TrySetPermutation, TrySpawnParticle, TrySpawnEntity, TryFillBlocks, TrySpawnItem, GetContractRoles, EntitysSort, GetPartner, EntityTranslate, BlockTranslate, ItemTranslate, HealthHigher, HealthBelow, DisplaceItemStack, DeleteItemStack, AlterDurability, CheckItemStack, SetDurability, DistanceAndName, PlayerInPower, IntelMessage, CompileSign, ToUnicode };
function SummoningEntityWithData(player, container, type) {
    const item = container?.getItem(player.selectedSlotIndex);
    const block = player.getBlockFromViewDirection({ maxDistance: 16 })?.block;
    const propertyID = item?.getDynamicPropertyIds().filter(type => !type.startsWith('reduction_pureness:'));
    const nameTag = item?.getDynamicProperty('reduction_pureness:name');
    const tags = item?.getDynamicProperty('reduction_pureness:tags');
    const entity = TrySpawnEntity(player.dimension, type, block?.center() ?? player.location);
    if (entity instanceof Error)
        return player.sendMessage(`§l§4<§c 召唤失败 §4>§r: ${entity.message}`);
    player.playSound('conduit.deactivate');
    server.system.run(() => entity.getComponent('tameable')?.tame(player));
    server.system.run(() => container.setItem(player.selectedSlotIndex));
    if (!item || !propertyID)
        return;
    server.system.runTimeout(() => propertyID.forEach(id => entity.setDynamicProperty(id, item.getDynamicProperty(id))), 20);
    if (!nameTag)
        return;
    server.system.runTimeout(() => entity.nameTag = nameTag, 15);
    if (!tags)
        return;
    JSON.parse(tags).forEach(tag => entity.addTag(tag));
}
;
function TrySetPermutation(object, type, value) {
    try {
        const state = object.permutation.withState(type, value);
        object.setPermutation(state);
    }
    catch (error) {
        return error;
    }
    ;
}
;
function TrySpawnParticle(dimension, typeID, location, molang) {
    try {
        dimension.spawnParticle(typeID, location, molang);
    }
    catch (error) {
        return error;
    }
}
;
function TrySpawnItem(dimension, item, location) {
    try {
        return dimension.spawnItem(item, location);
    }
    catch (error) {
        return error;
    }
}
;
function TryFillBlocks(dimension, begin, end, block, options) {
    try {
        return dimension.fillBlocks(new server.BlockVolume(begin, end), block, options);
    }
    catch (error) {
        return error;
    }
}
;
function TrySpawnEntity(dimension, typeID, location) {
    try {
        return dimension.spawnEntity(typeID, location);
    }
    catch (error) {
        return error;
    }
}
;
function EntitysSort(dimension, options, onSort, onFilter) {
    const entitys = onSort ? dimension.getEntities(options).sort(onSort) : dimension.getEntities(options);
    return onFilter ? entitys.filter(onFilter) : entitys;
}
;
function GetContractRoles(player, options, after) {
    const merge = {
        excludeTypes: ["minecraft:item", "minecraft:xp_orb", player.typeId],
        families: ['starry'],
        ...options
    };
    const roles = player.dimension.getEntities(merge).filter(role => role.getComponent('is_tamed'));
    roles.filter(role => role.getDynamicProperty('entity:contract_user') == player.id);
    roles.forEach(role => after(role));
}
;
function GetPartner(object, after) {
    const roleOptions = {
        location: object.location,
        families: ['starry'],
        maxDistance: 32
    };
    const playerOptions = {
        location: object.location,
        maxDistance: 32
    };
    const partner = [
        ...object.dimension.getEntities(roleOptions),
        ...object.dimension.getPlayers(playerOptions)
    ];
    const contract = object.getDynamicProperty('entity:contract_user');
    partner.forEach(entity => {
        if (entity.id != contract && entity.getDynamicProperty('entity:contract_user') != contract)
            return;
        after(entity);
    });
}
;
function EntityTranslate(object) {
    const Case = (intel) => {
        const proto = intel.typeId.split(':');
        if (intel.typeId == 'minecraft:player')
            return { text: intel.nameTag };
        else if (intel.nameTag.length >= 1)
            return { text: intel.nameTag };
        else
            return { translate: `entity.${(proto[0] == 'minecraft') ? proto[1] : intel.typeId}.name` };
    };
    const TypeID = (intel) => {
        const proto = intel.split(':');
        return { translate: `entity.${(proto[0] == 'minecraft') ? proto[1] : intel}.name` };
    };
    if (typeof object == 'string')
        return TypeID(object);
    else
        return Case(object);
}
;
function ItemTranslate(object) {
    const Case = (intel) => {
        const proto = intel.typeId.split(':');
        return { translate: `item.${(proto[0] == 'minecraft') ? proto[1] : intel.typeId}${(proto[0] == 'minecraft') ? '.name' : ''}` };
    };
    const TypeID = (intel) => {
        const proto = intel.split(':');
        return { translate: `item.${(proto[0] == 'minecraft') ? proto[1] : intel}${(proto[0] == 'minecraft') ? '.name' : ''}` };
    };
    if (typeof object == 'string')
        return TypeID(object);
    else
        return Case(object);
}
;
function BlockTranslate(object) {
    const Case = (intel) => {
        const proto = intel.typeId.split(':');
        return { translate: `tile.${(proto[0] == 'minecraft') ? proto[1] : intel.typeId}.name` };
    };
    const TypeID = (intel) => {
        const proto = intel.split(':');
        return { translate: `tile.${(proto[0] == 'minecraft') ? proto[1] : intel}.name` };
    };
    if (typeof object == 'string')
        return TypeID(object);
    else
        return Case(object);
}
;
function HealthBelow(health, percentage) {
    const current = health.currentValue;
    const maximum = health.defaultValue;
    return maximum * percentage >= current;
}
;
function HealthHigher(health, percentage) {
    const current = health.currentValue;
    const maximum = health.defaultValue;
    return maximum * percentage <= current;
}
;
function DeleteItemStack(container, sample) {
    for (let index = 0; index < container.size; index++) {
        const item = container.getItem(index);
        if (!item || item.typeId !== sample.typeId || item.amount < sample.amount)
            continue;
        if (item.amount > sample.amount) {
            item.amount -= sample.amount;
            container.setItem(index, item);
        }
        else
            container.setItem(index);
        return true;
    }
    ;
    return false;
}
;
function CheckItemStack(container, samples) {
    const types = new Map(samples.map(item => [item.typeId, item.amount]));
    const items = new Map();
    for (let index = 0; index < container.size; index++) {
        const item = container.getItem(index);
        if (!item)
            continue;
        items.set(item.typeId, item.amount);
    }
    ;
    return [...types].every(item => items.has(item[0]) && (items.get(item[0]) ?? 0 >= item[1]));
}
;
function DisplaceItemStack(container, proto, fresh, omitAmount) {
    const output = [];
    for (let index = 0; index < container.size; index++) {
        const item = container.getItem(index);
        if (!item || item.typeId != proto.typeId)
            continue;
        if (!omitAmount && proto.amount != item.amount)
            continue;
        if (proto.getLore.toString() != item.getLore.toString())
            continue;
        container.setItem(index, fresh);
        output.push(item);
    }
    ;
    return output;
}
;
function SetDurability(source, item, container, slot, value) {
    const durability = item.getComponent('minecraft:durability');
    if (!durability || !container)
        return;
    if (durability.damage <= durability.maxDurability - value) {
        durability.damage += value;
        container.setItem(slot, item);
    }
    else {
        container.setItem(slot);
        source.playSound('random.anvil_break');
    }
    ;
}
;
function AlterDurability(item, value) {
    const getDurability = item.getComponent('minecraft:durability');
    if (!getDurability)
        return item;
    if (getDurability.damage <= getDurability.maxDurability - value) {
        getDurability.damage += value;
        return item;
    }
    else
        return undefined;
}
;
function IntelMessage(object, range, text) {
    const setOptions = {
        location: object.location,
        maxDistance: range
    };
    const getPlayers = object.dimension.getPlayers(setOptions);
    getPlayers.forEach(info => info.onScreenDisplay.setActionBar(text));
}
;
function CompileSign(object, input, output) {
    const source = JSON.parse(object.getDynamicProperty(input));
    const getDimension = server.world.getDimension(source.dimension);
    output.set(input, { location: source.location, dimension: getDimension });
}
;
function PlayerInPower(object) {
    const players = object.dimension.getPlayers({ gameMode: server.GameMode.creative });
    const creative = players.filter(player => player.id == object.id).length != 0;
    return creative;
}
;
function ToUnicode(input) {
    const chars = input.split('');
    const compile = chars.map(char => {
        const code = char.charCodeAt(0);
        if (code >= 0x0041 && code <= 0x005A)
            return `\\u${code.toString(16).padStart(4, '0')}`;
        else if (code >= 0x0061 && code <= 0x007A)
            return `\\u${code.toString(16).padStart(4, '0')}`;
        else if (code >= 0x4E00 && code <= 0x9FA5)
            return `\\u${code.toString(16).padStart(4, '0')}`;
        else
            return char;
    }).join('');
    return compile
        .replace(/\\u0074\\u0072\\u0075\\u0065/g, 'true')
        .replace(/\\u0066\\u0061\\u006c\\u0073\\u0065/g, 'false');
}
;
function DistanceAndName(entity, distance) {
    return {
        rawtext: [
            { text: '§l' }, EntityTranslate(entity), { text: `\n§9距离: §5${distance}` }
        ]
    };
}
;
